package com.zbzly.video.service;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.bytedeco.ffmpeg.global.avcodec;
import org.bytedeco.ffmpeg.global.avutil;
import org.bytedeco.javacv.*;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class M3u8Service {
    private final String HTTP_PREFIX = "http://127.0.0.1:12321";
    public volatile static Cache<String, Byte[]> m3u8CacheMap = CacheBuilder
            .newBuilder()
            .expireAfterWrite(10, TimeUnit.SECONDS)
            .build();

    public void start2m3u8(String rtspUrl, String m3u8Url, String infoUrl) throws Exception {
        avutil.av_log_set_level(avutil.AV_LOG_INFO);
        FFmpegLogCallback.set();
        try (FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(rtspUrl)) {
            grabber.start();
            try (FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(m3u8Url,
                    grabber.getImageWidth(),
                    grabber.getImageHeight(),
                    grabber.getAudioChannels())) {

                // 格式化方式
                recorder.setFormat("hls");
                // hls切片时间
                recorder.setOption("hls_time", "1");
                // 播放列表保存条目
                recorder.setOption("hls_list_size", "10");
                // 复写文件条数
                recorder.setOption("hls_wrap", "10");
                recorder.setOption("hls_flags", "delete_segments");
                recorder.setOption("hls_delete_threshold", "1");
                recorder.setOption("hls_segment_type", "mpegts");
                recorder.setOption("hls_segment_filename", HTTP_PREFIX + "/video/upload/test-%d.ts");
                // 开启加密功能
                recorder.setOption("hls_key_info_file", infoUrl);
                // http属性
                recorder.setOption("method", HttpMethod.POST.name());
                recorder.setFrameRate(25);
                recorder.setGopSize(2 * 25);
                recorder.setVideoQuality(1.0);
                recorder.setVideoBitrate(10 * 1024);
                recorder.setVideoCodec(avcodec.AV_CODEC_ID_H264);
                recorder.setAudioCodec(avcodec.AV_CODEC_ID_AAC);
                recorder.start();
                long startTime = System.currentTimeMillis();
                long endTime = startTime + 60 * 1000;
                Frame frame;
                while ((frame = grabber.grabImage()) != null && endTime > System.currentTimeMillis()) {
                    try {
                        recorder.record(frame);
                    } catch (FrameRecorder.Exception ignored) {
                    }
                }
                recorder.setTimestamp(grabber.getTimestamp());
            }
        }
    }
}
